<template xmlns="http://www.w3.org/1999/html">
  <div class="p-2">
    <transition :enter-active-class="proxy?.animate.searchAnimate.enter" :leave-active-class="proxy?.animate.searchAnimate.leave">
      <div v-show="showSearch" class="mb-[10px]">
        <el-card shadow="hover">
          <el-form ref="queryFormRef" :model="queryParams" :inline="true">
            <el-form-item label="报单人名称" prop="receivingOrderId">
              <el-input v-model="queryParams.bdrmc"  clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="报单时间" prop="receivingOrderTime">
              <el-date-picker clearable
                v-model="queryParams.bdTime"
                type="date"
                value-format="YYYY-MM-DD"
                placeholder="请选择报单时间"
              />
            </el-form-item>
            <el-form-item label="所属区域" prop="deptId">
              <AreaSelector v-model="queryParams.deptId" />
            </el-form-item>
            <el-form-item>
              <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
              <el-button icon="Refresh" @click="resetQuery">重置</el-button>
            </el-form-item>
          </el-form>
        </el-card>
      </div>
    </transition>

    <el-card shadow="never">
      <template #header>
        <el-row :gutter="10" class="mb8">
<!--          <el-col :span="1.5">-->
<!--            <el-button type="primary" plain icon="Plus" @click="handleAdd" v-hasPermi="['wuliu:hdzb:add']">新增</el-button>-->
<!--          </el-col>-->
<!--          <el-col :span="1.5">-->
<!--            <el-button type="success" plain icon="Edit" :disabled="single" @click="handleUpdate()" v-hasPermi="['wuliu:hdzb:edit']">修改</el-button>-->
<!--          </el-col>-->
<!--          <el-col :span="1.5">-->
<!--            <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete()" v-hasPermi="['wuliu:hdzb:remove']">删除</el-button>-->
<!--          </el-col>-->
          <el-col :span="1.5">
            <el-button type="warning" plain icon="Download" @click="handleExport" v-hasPermi="['wuliu:hdzb:export']">导出</el-button>
          </el-col>
          <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>
      </template>

      <el-table v-loading="loading" :data="hdzbList" @selection-change="handleSelectionChange">
        <el-table-column label="发货厂家" prop="fhcjs" />
        <el-table-column label="报单人名称" prop="bdrmc" />
        <el-table-column label="区域" prop="deptId" />
        <el-table-column label="总件数" prop="wareSum">
          <template #default="{ row }"> {{ row.articleSum }}件 </template>
        </el-table-column>
        <el-table-column label="共计运费">
          <template #default="{ row }"> ￥{{ row.priceSum }} </template>
        </el-table-column>
        <el-table-column label="已付运费">
          <template #default="{ row }">
            <span>￥{{ row.paidAmount }}</span>
<!--            <el-button type="primary" size="small" :style="{ marginLeft: '2px' }" text @click="handleOpenModifyPaidAmount(row)">-->
<!--              <el-icon> <EditPen /></el-icon>-->
<!--            </el-button>-->
          </template>
        </el-table-column>
        <el-table-column label="垫付运费">
          <template #default="{ row }"> ￥{{ row.dfyfs || 0 }} </template>
        </el-table-column>
        <el-table-column label="叉车费">
          <template #default="{ row }"> ￥{{ row.ccfs || 0  }} </template>
        </el-table-column>
        <el-table-column label="其他费用">
          <template #default="{ row }"> ￥{{ row.qtfys  || 0 }} </template>
        </el-table-column>
        <!--      <el-table-column label="结算状态">-->
        <!--        <template #default="{ row }">{{ OrderPaymentStatusInfo[row.paymentStatus] }}</template>-->
        <!--      </el-table-column>-->
        <el-table-column label="报单时间" prop="createTime" />
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
<!--          <template #default="scope">-->
<!--            <el-tooltip content="修改" placement="top">-->
<!--              <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['wuliu:hdzb:edit']"></el-button>-->
<!--            </el-tooltip>-->
<!--            <el-tooltip content="删除" placement="top">-->
<!--              <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['wuliu:hdzb:remove']"></el-button>-->
<!--            </el-tooltip>-->
<!--          </template>-->
          <template #default="{ row }">
<!--                        <el-tooltip content="修改" placement="top">-->
<!--                          <el-button link type="primary" icon="Edit" @click="handleOpenModifyPaidAmount(row)"></el-button>-->
<!--                        </el-tooltip>-->
<!--                        <el-tooltip content="删除" placement="top">-->
<!--                          <el-button link type="primary" icon="Delete" @click="handleDelete(row)" v-hasPermi="['wuliu:hdzb:remove']"></el-button>-->
<!--                        </el-tooltip>-->
            <el-button type="primary" size="small" text @click="handleOpenModifyPaidAmount(row)">修改</el-button>
            <el-button type="primary" size="small" text @click="handleExportForId(row.id)">导出</el-button>
            <el-button :icon="Search" type="primary" size="small" text @click="openMx(row)"> 查看 </el-button>

            <!--          <router-link to="/drivecar">About Page</router-link>-->
          </template>
        </el-table-column>
      </el-table>

      <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize" @pagination="getList" />
    </el-card>
    <!-- 添加或修改回单主表对话框 -->
    <el-dialog :title="dialog.title" v-model="dialog.visible" width="500px" append-to-body>
      <el-form ref="hdzbFormRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="已支付金额" prop="paidAmount">
          <el-input v-model="form.paidAmount" placeholder="请输入已支付金额" />
        </el-form-item>
        <el-form-item label="垫付运费" prop="dfyfs">
          <el-input v-model="form.dfyfs" placeholder="请输入已支付金额" />
        </el-form-item>
        <el-form-item label="叉车费" prop="ccfs">
          <el-input v-model="form.ccfs" placeholder="请输入已支付金额" />
        </el-form-item>
        <el-form-item label="其他费用" prop="qtfys">
          <el-input v-model="form.qtfys" placeholder="请输入已支付金额" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
    <el-drawer v-model="detailVisible" title="订单信息" direction="rtl" size="60%">
      <el-table :data="orderMxRef">
        <el-table-column prop="customName" label="收货人名称" />
        <el-table-column prop="number" label="件数" />
        <el-table-column prop="area" label="方数" />
        <el-table-column prop="univalence" label="单价" />
        <el-table-column prop="totalPrice" label="总运费">
<!--          <el-button type="primary" size="small" :style="{ marginLeft: '2px' }" text @click="handleOpenModifyPaidAmount(row)">-->
<!--            <el-icon> <EditPen /></el-icon>-->
<!--          </el-button>-->
          <template #default="{ row }">
            <span>￥{{ row.totalPrice }}</span>
<!--            <el-button type="primary" size="small" :style="{ marginLeft: '2px' }" text @click="handleOpenModifyPaidAmountMx(row)">-->
<!--              <el-icon> <EditPen /></el-icon>-->
<!--            </el-button>-->
          </template>
        </el-table-column>


        <el-table-column prop="createTime" label="创建时间" />
      </el-table>
    </el-drawer>

    <el-dialog v-model="modifyPaidAmountVisible" title="修改运费" width="300" :before-close="beforeModifyClose">
      <span>已付运费：</span>  <el-input-number v-model="modifyItem.paidAmount" :min="0" :precision="2" />
      <br><span>垫付运费：</span>  <el-input-number v-model="modifyItem.dfyfs" :min="0" :precision="2" />
      <br> <span>叉车运费：</span>  <el-input-number v-model="modifyItem.ccfs" :min="0" :precision="2" />
      <br><span>其他费用：</span>  <el-input-number v-model="modifyItem.qtfys" :min="0" :precision="2" />
      <template #footer>
        <div class="dialog-footer">
          <el-button :disabled="requesting" @click="handleCloseModifyPaidAmount">取消</el-button>
          <el-button :loading="requesting" :disabled="requesting" type="primary" @click="handleUpdateItem">提交</el-button>
        </div>
      </template>
    </el-dialog>


<!--    <el-dialog v-model="modifyPaidAmountVisible2" title="修改已垫付运费" width="300" :before-close="beforeModifyClose">-->
<!--      <el-input-number v-model="modifyItem.paidAmount" :min="0" :precision="2" />-->

<!--      <template #footer>-->
<!--        <div class="dialog-footer">-->
<!--          <el-button :disabled="requesting" @click="handleCloseModifyPaidAmount">取消</el-button>-->
<!--          <el-button :loading="requesting" :disabled="requesting" type="primary" @click="handleUpdateItem">提交</el-button>-->
<!--        </div>-->
<!--      </template>-->
<!--    </el-dialog>-->
  </div>
</template>

<script setup name="Hdzb" lang="ts">
import { listHdzb, getHdzb, delHdzb, addHdzb, updateHdzb } from '@/api/wuliu/hdzb';
import { HdzbVO, HdzbQuery, HdzbForm } from '@/api/wuliu/hdzb/types';
import AreaSelector from '@/components/AreaSelector/AreaSelector.vue';
import { Search } from '@element-plus/icons-vue';
import OrderMx from '@/components/OrderMx/OrderMx.vue';
import { WaresDocVo } from '@/api/wuliu/wares/types';
import { updateHdWares, updateWares } from '@/api/wuliu/wares';
import { HdwareDocMxVo } from '@/api/wuliu';

const { proxy } = getCurrentInstance() as ComponentInternalInstance;

const hdzbList = ref<HdzbVO[]>([]);
const buttonLoading = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref<Array<string | number>>([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);

const queryFormRef = ref<ElFormInstance>();
const hdzbFormRef = ref<ElFormInstance>();

const dialog = reactive<DialogOption>({
  visible: false,
  title: ''
});

const initFormData: HdzbForm = {
  id: undefined,
  paidAmount: undefined,
  dfyfs: undefined,
  ccfs: undefined,
  qtfys: undefined

}
const data = reactive<PageData<HdzbForm, HdzbQuery>>({
  form: {...initFormData},
  queryParams: {
    dfyfs: undefined,
    ccfs: undefined,
    qtfys: undefined
  },
  rules: {
  }
});

const { queryParams, form, rules } = toRefs(data);

const formu = {
  id: undefined,
  paidAmount: undefined,
  dfyfs: undefined,
  ccfs: undefined,
  qtfys: undefined
}

/** 查询回单主表列表 */
const getList = async () => {
  loading.value = true;
  const res = await listHdzb(queryParams.value);
  hdzbList.value = res.rows;
  total.value = res.total;
  loading.value = false;
}

/** 取消按钮 */
const cancel = () => {
  reset();
  dialog.visible = false;
}

/** 表单重置 */
const reset = () => {
  form.value = {...initFormData};
  hdzbFormRef.value?.resetFields();
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value?.resetFields();
  handleQuery();
}

/** 多选框选中数据 */
const handleSelectionChange = (selection: HdzbVO[]) => {
  ids.value = selection.map(item => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
const handleAdd = () => {
  reset();
  dialog.visible = true;
  dialog.title = "添加回单主表";
}

/** 修改按钮操作 */
const handleUpdate = async (row?: HdzbVO) => {
  reset();
  const _id = row?.id || ids.value[0]
  const res = await getHdzb(_id);
  Object.assign(form.value, res.data);
  dialog.visible = true;
  dialog.title = "修改回单主表";
}

/** 提交按钮 */
const submitForm = () => {
  hdzbFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      buttonLoading.value = true;
      if (form.value.id) {
        await updateHdzb(form.value).finally(() =>  buttonLoading.value = false);
      } else {
        await addHdzb(form.value).finally(() =>  buttonLoading.value = false);
      }
      proxy?.$modal.msgSuccess("操作成功");
      dialog.visible = false;
      await getList();
    }
  });
}

/** 删除按钮操作 */
const handleDelete = async (row?: HdzbVO) => {
  const _ids = row?.id || ids.value;
  await proxy?.$modal.confirm('是否确认删除回单主表编号为"' + _ids + '"的数据项？').finally(() => loading.value = false);
  await delHdzb(_ids);
  proxy?.$modal.msgSuccess("删除成功");
  await getList();
}

/** 导出按钮操作 */
const handleExport = () => {
  proxy?.download('wuliu/hdzb/export2', {
    ...queryParams.value
  }, `hdzb_${new Date().getTime()}.xlsx`)
}

onMounted(() => {
  getList();
});

/** 导出按钮操作 */
const handleExportForId = (id) => {
  proxy?.download('wuliu/hdzb/export2', {
    id
  }, `hdzb_${new Date().getTime()}.xlsx`)
}

//查看明细
// function openMx(item: any) {
//   console.log('Mx', item.wareDocMxVoList);
//   orderMxRef.value?.handleOpen(item.wareDocMxVoList);
// }
const orderMxRef = ref<InstanceType<typeof OrderMx>>();
const detailVisible = ref(false);

async function openMx(item: SjWareDocVo) {
  console.log('Detail', item);
  orderMxRef.value = item.hdwareDocMxVoList;
  detailVisible.value = true;
}
const requesting = ref(false);
const modifyItem = ref<WaresDocVo>();
const modifyPaidAmountVisible = ref(false);

function handleOpenModifyPaidAmount(item: WaresDocVo) {
  modifyItem.value = { ...toRaw(item) };
  modifyPaidAmountVisible.value = true;
}

function handleOpenModifyPaidAmountMx(item: HdwareDocMxVo) {
  modifyItem.value = { ...toRaw(item) };
  modifyPaidAmountVisible.value = true;
}

function handleCloseModifyPaidAmount() {
  modifyPaidAmountVisible.value = false;
}
async function handleUpdateItem() {
  const item = toRaw(modifyItem.value);

  if (!item) {
    return;
  }

  try {
    requesting.value = true;
    const { id, paidAmount,dfyfs,ccfs,qtfys } = item;
    await updateHdWares({ id, paidAmount,dfyfs,ccfs,qtfys });
    console.log('update item', item);
  } catch (error) {
    console.error('Error update item', error);
  } finally {
    requesting.value = false;
    handleCloseModifyPaidAmount();
    handleQuery();
  }
}

async function handleUpdateMxItem() {
  const item = toRaw(orderMxRef.value);

  if (!item) {
    return;
  }

  try {
    requesting.value = true;
    const { id, paidAmount } = item;
    await updateHdWares({ id, paidAmount });
    console.log('update item', item);
  } catch (error) {
    console.error('Error update item', error);
  } finally {
    requesting.value = false;
    handleCloseModifyPaidAmount();
    handleQuery();
  }
}

</script>
